import axios from 'axios';
import { message } from 'antd';
import { mockUrl } from './webUrl';

// fastmock网站
const baseApi = mockUrl();

/**
 * 封装axios库, 函数返回的是一个promise
 * url  [string] 请求地址
 * data [object] 请求参数
 * type [string] 请求类型
 * isShowLoading [Boolean] 是否显示正在加载
 */
export default function ajax(
  url: string,
  data = {},
  type = 'get',
  isShowLoading = true
) {
  let reqParams: any = { baseURL: baseApi, timeout: 5000 };
  if (isShowLoading) {
    (document as any).getElementById('ajaxLoading').style.display = 'block';
  }

  if (type.toLowerCase() === 'get') {
    reqParams.method = 'get';
    reqParams.url = url;
    reqParams.params = data;
  } else if (type.toLowerCase() === 'post') {
    reqParams.method = 'post';
    reqParams.url = url;
    reqParams.data = data;
  }

  return new Promise((resolve, reject) => {
    axios(reqParams)
      .then((response: any) => {
        if (isShowLoading) {
          (document as any).getElementById('ajaxLoading').style.display =
            'none';
        }
        if (response.status === 200) {
          if (response.data.status === 1) {
            resolve(response.data.data);
          } else {
            message.info(response.data.msg);
          }
        } else {
          reject(response.data);
        }
      })
      .catch((error: any) => {
        message.error('网络错误，请稍后重试');
      });
  });
}
